
package com.platform.modules.job.task;

import com.platform.common.utils.Constant;
import com.platform.common.utils.StringUtils;
import com.platform.modules.mall.activity.service.GoShoppingService;
import com.platform.modules.mall.entity.MallOrderEntity;
import com.platform.modules.mall.entity.MallOrderGoodsEntity;
import com.platform.modules.mall.service.MallCardSnService;
import com.platform.modules.mall.service.MallGoodsService;
import com.platform.modules.mall.service.MallOrderGoodsService;
import com.platform.modules.mall.service.MallOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单定时任务
 * orderTask为spring bean的名称
 *
 * @author
 */
@Slf4j
@Component("orderTask")
public class OrderTask {
    @Resource
    private MallOrderService orderService;
    @Resource
    private MallGoodsService goodsService;

    @Autowired
    private MallCardSnService mallCardSnService;

    @Autowired
    private MallOrderGoodsService mallOrderGoodsService;
    @Autowired
    private GoShoppingService goShoppingService;

    /**
     * 过期自动取消订单
     */
    @SuppressWarnings(value = "unused")
    @Transactional(rollbackFor = Exception.class)
    public void expireOrder() {
        log.info("--------------------------开始执行过期自动取消订单任务--------------------------");

        //等待付款的订单
        List<MallOrderEntity> orderList = orderService.lambdaQuery().lt(MallOrderEntity::getOrderStatus, Constant.OrderStatus.YGQ.getValue()).list();
        if (null != orderList && !orderList.isEmpty()) {
            log.info("待付款订单数：" + orderList.size());

            List<MallOrderEntity> list = new ArrayList<>();

            //当前时间大于过期时间
            orderList.stream().filter(item -> new Date().after(item.getExpireTime()))
                    .forEach(order -> {
                        if (StringUtils.isNotBlank(order.getActivityId())) {
                            goShoppingService.cancelOrder(order);
                        } else {
                            order.setOrderStatus(Constant.OrderStatus.YQX.getValue());
                            list.add(order);

                            //取消的订单释放商品库存
                            goodsService.backGoodsNumber(order);
                        }
                    });
            if (list.size() > 0) {
                orderService.updateBatchById(list);
            }
        }
        log.info("--------------------------结束过期自动取消订单任务--------------------------");
    }

    public void sendCard() {
        List<MallOrderEntity> orderInfoList = orderService.lambdaQuery().eq(MallOrderEntity::getPayStatus, Constant.PayStatus.YFK.getValue())
                .eq(MallOrderEntity::getOrderStatus, Constant.OrderStatus.YFK.getValue()).eq(MallOrderEntity::getOrderType, Constant.CARD_ORDER).list();

        if (null != orderInfoList && !orderInfoList.isEmpty()) {
            log.info("待发券订单数：" + orderInfoList.size());
            for (MallOrderEntity orderInfo : orderInfoList) {
                MallOrderGoodsEntity mallOrderGoodsEntity = mallOrderGoodsService.querySumMarketPrice(orderInfo.getId());
                if (mallOrderGoodsEntity.getMarketPrice().compareTo(orderInfo.getActualPrice()) != 1) {
                    continue;
                }
                try {
                    mallCardSnService.sendCard(orderInfo);
                    //卡券发放中
                    orderInfo.setOrderStatus(Constant.OrderStatus.YFH.getValue());
                    orderInfo.setShippingStatus(Constant.ShippingStatus.YFH.getValue());
                    orderService.updateById(orderInfo);
                } catch (Exception e) {
                    log.error("订单：{}，发送卡券出现异常", orderInfo.getOrderSn());
                    e.printStackTrace();
                }
            }
        }
        log.info("--------------------------自动发券订单任务--------------------------");
    }


    /**
     * @startuml participant OrderService
     * participant OrderTask
     * participant MallCardSnService
     * participant SendCoupon
     * participant 微信服务商 as kaquan
     * <p>
     * OrderTask -> OrderService:查看所有的卡券订单
     * activate OrderTask
     * activate OrderService
     * OrderService -> OrderTask:返回卡券集合
     * deactivate OrderService
     * loop 循环所有卡券订单
     * OrderTask -> MallCardSnService:给订单发送卡券
     * activate MallCardSnService
     * MallCardSnService ->MallCardSnService:处理订单信息
     * MallCardSnService->SendCoupon:发送卡券
     * activate SendCoupon
     * alt 微信卡券
     * SendCoupon ->kaquan:发送卡券
     * activate kaquan
     * kaquan->SendCoupon:返回结果
     * deactivate kaquan
     * else 本系统卡券
     * SendCoupon->SendCoupon:发送系统卡券
     * end
     * SendCoupon->MallCardSnService:返回发送结果
     * deactivate SendCoupon
     * MallCardSnService->OrderTask:返回订单处理结果
     * deactivate MallCardSnService
     * end
     * @enduml 暂不使用，需要改动很多东西，现在只是调整上面的方法位置，对处理细节没有修改
     * <p>
     * 1.查看所有需要发卷的订单
     * 2.处理单个订单，修改订单状态，减扣卡券批次
     * 3.发送微信卡券，确定发送卡券错误时，抛出异常
     * 4.单个订单异常，不影响其它订单
     */

    public void sendCardNew() {
        List<MallOrderEntity> orderInfoList = orderService.lambdaQuery().eq(MallOrderEntity::getPayStatus, Constant.PayStatus.YFK.getValue())
                .eq(MallOrderEntity::getOrderStatus, Constant.OrderStatus.YFK.getValue()).eq(MallOrderEntity::getOrderType, Constant.CARD_ORDER).list();
        if (null != orderInfoList && !orderInfoList.isEmpty()) {
            log.info("待发券订单数：" + orderInfoList.size());
            for (MallOrderEntity orderInfo : orderInfoList) {
                try {
                    mallCardSnService.sendCard2(orderInfo);
                } catch (Exception e) {
                    log.error("订单：{}，发送卡券出现异常", orderInfo.getOrderSn());
                    e.printStackTrace();
                }
            }
        }
        log.info("--------------------------卡券定时任务 end--------------------------");
    }
}
